package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        TurnoverReportVO vo = new TurnoverReportVO();

        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end",endTime);

            Double turnover = orderMapper.getSumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //组装vo
        vo.setDateList(StringUtils.join(dates,","));
        vo.setTurnoverList(StringUtils.join(turnoverList,","));

        return vo;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        ArrayList<Integer> newUserList = new ArrayList<>(); //新增用户数列表
        ArrayList<Integer> totalUserList = new ArrayList<>(); //新增用户数列表

        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("end",endTime);
            Integer newUser  = userMapper.getCountByMap(map);
            newUserList.add(newUser);
            map.put("begin",beginTime);
            Integer totalUser = userMapper.getCountByMap(map);
            totalUserList.add(totalUser);
        }

        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();

        return vo;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        ArrayList<Integer> validOrderCount = new ArrayList<>(); //每日有效订单数
        ArrayList<Integer> totalOrderCount = new ArrayList<>(); //每日订单总数

        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer validCount = orderMapper.getOrderCount(beginTime,endTime,Orders.COMPLETED);
            validOrderCount.add(validCount);
            Integer totalCount = orderMapper.getOrderCount(beginTime,endTime,null);
            totalOrderCount.add(totalCount);

        }

        Integer validOrderCountAll = validOrderCount.stream().reduce(Integer::sum).get();
        Integer totalOrderCountAll = totalOrderCount.stream().reduce(Integer::sum).get();

        //订单完成率 = 有效订单 / 订单总数
        Double orderCompletionRate = 0.0;
        if (totalOrderCountAll != 0) {
            orderCompletionRate = validOrderCountAll.doubleValue() / totalOrderCountAll;
        }

        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dates, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(totalOrderCount,","))
                .totalOrderCount(totalOrderCountAll)
                .validOrderCount(validOrderCountAll)
                .validOrderCountList(StringUtils.join(validOrderCount, ","))
                .build();
        return vo;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.top10(beginTime,endTime);

        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,",")).build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //获取30天前的日期和昨天的日期
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO vo = workSpaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX));

        try {
            // FileInputStream inputStream = new FileInputStream("C:\\Users\\zhulan\\Desktop\\cangqiong168\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx");
            FileInputStream inputStream = new FileInputStream("C:\\Users\\zhulan\\Desktop\\cangqiong168\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream("C:\\Users\\zhulan\\Desktop\\cangqiong168\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));
            XSSFSheet sheet = excel.getSheetAt(0);
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            XSSFRow row3 = sheet.getRow(3);
            row3.getCell(2).setCellValue(vo.getTurnover());
            row3.getCell(4).setCellValue(vo.getOrderCompletionRate());
            row3.getCell(6).setCellValue(vo.getNewUsers());
            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(vo.getValidOrderCount());
            row4.getCell(4).setCellValue(vo.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                vo = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(vo.getTurnover());
                row.getCell(3).setCellValue(vo.getValidOrderCount());
                row.getCell(4).setCellValue(vo.getOrderCompletionRate());
                row.getCell(5).setCellValue(vo.getUnitPrice());
                row.getCell(6).setCellValue(vo.getNewUsers());
            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            excel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}























